package com.yundahh.u8c.dao.base;

import com.yundahh.u8c.config.U8CConfig;
import com.yundahh.u8c.entity.base.U8CResult;
import com.yundahh.u8c.enums.OperationType;
import com.yundahh.u8c.exception.U8CApiException;
import com.yundahh.u8c.util.HttpUtils;
import com.yundahh.u8c.util.JsonUtils;

import java.io.IOException;
import java.util.HashMap;

public abstract class U8CBaseDao<T> {

    protected U8CConfig config;

    public abstract Class<T> getClazz();

    public abstract String getApiUrl();

    public U8CBaseDao(U8CConfig config) {
        this.config = config;
    }

    public U8CResult<T> send(OperationType operationType, HashMap params) throws IOException, U8CApiException {
        return send(operationType, JsonUtils.object2Json(params));
    }

    public U8CResult<T> send(OperationType operationType,String json) throws IOException, U8CApiException {
        String jsonResult = HttpUtils.sendPost(config.getServerUrl()+getApiUrl()+"/"+operationType.getValue(), config.getHeaders(), json);
        U8CResult<T> parse =null;
        switch (operationType){
            case INSERT:
                parse = JsonUtils.parseInsert(jsonResult, getClazz());
                break;
            case APPROVE:
                parse = JsonUtils.parseStringData(jsonResult);
                break;
            default:
                parse = JsonUtils.parseQuery(jsonResult, getClazz());
        }
        return parse;
    }
}
